package com.zf.websocket.handle;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 使用通配符进行路径匹配，见 {@link com.zf.websocket.config.WebSocketConfig}
 */
@Component
public class PathHandler extends AbstractWebSocketHandler {
    public static final ConcurrentHashMap<String, WebSocketSession> USERS = new ConcurrentHashMap<>();

    /**
     * 建立连接后执行
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 获取域名之后的请求路径字符串
        String path = session.getUri().getPath();
        System.out.println(path);
        System.out.println(session.getId() + " 建立连接");
        USERS.put(session.getId(), session);
    }

    /**
     * 处理文本消息
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println(session.getId() + " 文本消息：" + message.getPayload());
    }

    /**
     * 消息传输过程中出错后执行
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println(session.getId() + " 消息出错: " + exception);
    }

    /**
     * 断开连接后执行
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        USERS.remove(session.getId());
        System.out.println(session.getId() + " 断开连接：" + status);
    }
}
